package com.crt.uav.rabbitmq.consumer.listener;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.crt.uav.Constants;
import com.crt.uav.common.utils.JSON;
import com.crt.uav.persistence.entity.UavApiLog;
import com.crt.uav.persistence.service.UavApiLogService;
import com.crt.uav.rabbitmq.consumer.AbstractExtChannelAwareMessageListener;

@Component
public class UavInspectionRecordMessageListener extends AbstractExtChannelAwareMessageListener {

    //无人机执行完毕返回信息
    private String queueName = "uav.inspection.record.queue";

    private String persistFlag = Constants.PERSISTFLAG_YES;

    @Autowired(required = false)
    @Qualifier("uavApiLogService")
    private UavApiLogService uavApiLogService;

    // @Autowired(required = false)
    // @Qualifier("thRabbitMqTemplate")
    // private RabbitTemplate thRabbitMqTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(UavInspectionRecordMessageListener.class);

    // @Override
    // protected void handleMessage(Message message, Channel channel) {
    // // 这里可以添加处理逻辑，例如解析消息内容、存储到数据库等
    // thRabbitMqTemplate.convertAndSend(message.getMessageProperties().getReceivedExchange(),
    // message.getMessageProperties().getReceivedRoutingKey(), message.getBody());
    // LOGGER.info("消息发送成功，Exchange: {}, RoutingKey: {}, Body: {}",
    // message.getMessageProperties().getReceivedExchange(),
    // message.getMessageProperties().getReceivedRoutingKey(),
    // new String(message.getBody()));
    // }

    @Override
    public String getQueueName() {
        return queueName;
    }

    public String getPersistFlag() {
        return persistFlag;
    }

    @Override
    protected void handelPersistMethod(Message message) {
        // 这里可以添加处理逻辑，例如解析消息内容、存储到数据库等
        try {
            UavApiLog uavApiLog = new UavApiLog();
            uavApiLog.setProtocol("MQ");
            uavApiLog.setMethod(getQueueName());
            Map<String, String > respBodyMap = new HashMap<>();
            respBodyMap.put("messageId", message.getMessageProperties().getMessageId());
            respBodyMap.put("exchange", message.getMessageProperties().getReceivedExchange());
            respBodyMap.put("routingKey", message.getMessageProperties().getReceivedRoutingKey());
            respBodyMap.put("body", new String(message.getBody()));
            respBodyMap.put("queue", getQueueName());
            uavApiLog.setRespBody(JSON.stringify(respBodyMap));
            uavApiLogService.save(uavApiLog);
            LOGGER.info("队列 {},持久化消息方法成功", getQueueName());
        } catch (Exception e) {
            LOGGER.error("队列 {},持久化消息方法失败", getQueueName(), e);
        }
    }
}
